package cvc.framework.webSocket;

import com.alibaba.fastjson.JSONObject;
import cvc.framework.entity.CustomerMes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@ServerEndpoint("/websocket/{userId}")
@Component
public class WebSocket {
    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static int onlineCount = 0;
    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     */
    private static ConcurrentHashMap<String, WebSocket> webSocketMap = new ConcurrentHashMap<>();
    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;
    /**
     * 接收userId
     */
    private String userId = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        try {
            if (webSocketMap.containsKey(userId)) {
                webSocketMap.remove(userId);
                webSocketMap.put(userId, this);
                //加入set中
            } else {
                webSocketMap.put(userId, this);
                //加入set中
                addOnlineCount();
                //在线数加1
            }

            System.out.println(userId + "登录，当前在线人数：" + onlineCount);
//            sendMessage("连接成功");
        } catch (Exception e) {
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            //从set中删除
            subOnlineCount();
        }
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(byte[] message) {
        for (WebSocket item : webSocketMap.values()) {
            try {
                item.session.getBasicRemote().sendBinary(ByteBuffer.wrap(message));
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    @OnMessage
    public void onMessage(String message) {
        ExecutorService ex = Executors.newCachedThreadPool();
        ex.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject jsonSwitch = JSONObject.parseObject(message);
                    String head = jsonSwitch.getString("uuid");
                    String meg = jsonSwitch.getString("message");
                    AddMessageToMap amtm = new AddMessageToMap();
                    amtm.addMap(head, meg);
                } catch (Exception e) {
                    System.out.println(e);
                }


            }
        });
        ex.shutdown();
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public synchronized void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocket.onlineCount--;
    }


    /**
     * 给某个用户发送消息
     */
    public static boolean sendMessageToUser(String userId, String message) {
        try {
            if (webSocketMap.get(userId) != null) {
                webSocketMap.get(userId).sendMessage(message);
                System.out.println("数据发送成功：" + message);
                return true;
            } else {
                System.out.println(userId + "不在线");
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }


}